#include "toast.h"

#include <QApplication>
#include <QLabel>
#include <QScreen>
#include <QTimer>
#include <QVBoxLayout>

Toast::Toast(const QString& text)
{
    // 1.窗口基本属性
    this->setFixedSize(500, 100);
    this->setWindowFlags(Qt::FramelessWindowHint);      // 去掉qt窗口边框
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setStyleSheet("QDialog { background-color: rgb(255, 255, 255); }");

    // 2.窗口定位
    QScreen* screen = QApplication::primaryScreen();
    int screenWidth = screen->size().width();
    int screenHeight= screen->size().height();
    int x = screenWidth - this->width() >> 1;
    int y = screenHeight - this->height() - 100;
    this->move(x, y);

    // 3.垂直布局
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    this->setLayout(layout);

    QLabel* label = new QLabel();
    label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    label->setAlignment(Qt::AlignCenter);
    label->setText(text);
    label->setStyleSheet("QLabel { font-size: 18px; }");
    layout->addWidget(label);

    // 4. 2s自动关闭窗口
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=]() {
        timer->stop();
        this->close();
    });

    timer->start(2000);
}

void Toast::showMessage(const QString& text)
{
    Toast* toast = new Toast(text);
    toast->show();
}
